package com.matrix.draft.sockettest.nettychatroom;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // handlerAdded表示连接建立, 这个方法第一个执行
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        Channel ch = ctx.channel();
        channelGroup.add(ch);
        channelGroup.writeAndFlush("[@" + ch.remoteAddress() + "加入聊天室]");
        /**Delete**/System.out.println("[@" + ch.remoteAddress() + "加入聊天室]");/**Delete**/
    }

    // handlerRemoved表示handler被移除,channelGroup中也会自动移除它(因为add时候使用了监听器)
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        Channel ch = ctx.channel();
        channelGroup.writeAndFlush("[@"+ch.remoteAddress()+"离开了聊天室]");
        /**Delete**/System.out.println("[@"+ch.remoteAddress()+"离开了聊天室]");/**Delete**/
    }

    // 当Channel处于非活跃状态
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel ch = ctx.channel();
        channelGroup.writeAndFlush("[@" + ch.remoteAddress() + "离线了]");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        Channel ch = ctx.channel();
        // 转发给所有channel
        channelGroup.remove(ch); // 先移除自己
        channelGroup.writeAndFlush("@"+ch.remoteAddress()+" : "+msg); // 发送给所有用户
        channelGroup.add(ch); // 在把自己加上去
        /**Delete**/System.out.println("@"+ch.remoteAddress()+" : "+msg);/**Delete**/
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
